package com.spring.arch.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.spring.arch.common.security.SecurityProperties;
import com.spring.arch.common.security.UserPrincipal;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;


/**
 * 应用核心配置
 *
 * @author Frank
 * @version 1.0.0.1
 * @since 2019/12/7 15:43
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class ApplicationConfiguration {

    @Bean
    public SecurityProperties securityProperties() {
        return new SecurityProperties();
    }

    @Bean("tokenLocalCache")
    public Cache<String, UserPrincipal> buildTokenCache() {
        Integer timeout = securityProperties().getAuth().getDefaultAccessTokenTimeout();
        // 通过CacheBuilder构建一个缓存实例
        return CacheBuilder.newBuilder()
                // 设置缓存的最大容量
                .maximumSize(1000)
                // 设置失效时间为JWT的失效时间
                .expireAfterWrite(timeout, TimeUnit.MILLISECONDS)
                // 并发数为cpu核心进程数
                .concurrencyLevel(Runtime.getRuntime().availableProcessors())
                // 开启缓存统计
                .recordStats()
                .build();
    }
}